<script setup lang="ts">
import {Feature, Map, View} from "ol";
import * as control from 'ol/control';
import * as coordinate from 'ol/coordinate';
import * as proj from 'ol/proj';
import * as geom from 'ol/geom';
import * as style from 'ol/style';
import TileLayer from "ol/layer/Tile";
import LayerVector from 'ol/layer/Vector'
import SourceVector from 'ol/source/Vector'
import Draw from 'ol/interaction/Draw'
import {XYZ} from "ol/source";
import {onMounted, ref,onUnmounted} from "vue";
import source = ol.source;
import {returnMessage} from "../network/webSocket.ts";
import VectorSource from "ol/source/Vector";
import VectorLayer from "ol/layer/Vector";
import Point from "ol/geom/Point";
import {transform} from "ol/proj";
import Overlay from "ol/Overlay";
import sourceVector from "ol/source/Vector";
import layerVecor from "ol/layer/Vector";
import iconPng from '../assets/icon.png'


const map = ref(null) // 存放地图实例
const mousePositionTxt = ref([102.064839, 24.548857])
const currentCoordinate = ref([102.064839, 24.548857])
const scaleLineControl = ref(null) //比例尺
let coordinateSign = ref(0) //是否显示经纬度
const tool = ref('Polygon')
let points = ref(null)

let curLoc = ref(JSON.parse(returnMessage.value))
console.log("MapUserLoc:",curLoc.value)


const count = ref(0);

// 创建定时器
let intervalId;

// 在组件挂载时启动定时器
onMounted(() => {

  intervalId = setInterval(() => {
    if(count.value<100){
      count.value++;
      // console.log(JSON.parse(returnMessage.value))
      curLoc.value = JSON.parse(returnMessage.value)
      console.log(count.value)
      // console.log(curLoc.value)
    }
  }, 2000); // 1000毫秒，即1秒

});

// 在组件卸载时清除定时器，防止内存泄漏
onUnmounted(() => {
  clearInterval(intervalId);
});



const sourceDraw = new SourceVector({
  wrapX: false // 禁止横向无限重复（底图渲染的时候会横向无限重复），设置了这个属性，可以让绘制的图形不跟随底图横向无限重复
})
// 绘图层
let drawVector = new LayerVector({
  source: sourceDraw
})

let iconFeature = new Feature({
  // geometry: new Point([0, 0]), // 图标展示的位置
  geometry: new Point(transform([curLoc.value.curLongitude, curLoc.value.curLatitude], 'EPSG:4326', 'EPSG:3857')),
  name: '你点我了',
  population: 4000,
  rainfall: 500
})


// 创建图标样式
let iconStyle = new style.Style({
  image: new style.Icon({ // 定义图标锚点
    //锚点是给图标位置 做 微调的
    anchor: [2, 1.2], // 根据图标的大小，对应上面 [0, 0] 的坐标
    anchorXUnits: 'fraction',
    anchorYUnits: 'pixels',
    src: iconPng,
    scale: 0.2 //整体设置图片大小
  })
})

// 把样式应用到图标上
iconFeature.setStyle(iconStyle)

// 创建矢量容器，将图标特性添加进容器中
let vectorSource = new sourceVector({
  features: [iconFeature]
})

// 创建矢量图层
let vectorLayer = new layerVecor({
  source: vectorSource
})
const shopPopup = ref(false)
const popupCom = ref(null)
const popup = ref(null)

function initMap () {
  scaleLineControl.value = new control.ScaleLine()//默认是 米制单位
  // 地图实例
  map.value = new Map({
    target: 'map1',                         // 对应页面里 id 为 map1 的元素
    layers: [                              // 图层
      new TileLayer({
        source: new XYZ({
          url:"http://t0.tianditu.com/DataServer?T=img_w&x={x}&y={y}&l={z}&tk=f0205b3015ed23553ee037f6ecac9b19",
          wrapX: false
        }),
        preload: Infinity,//底图预加载。减少缩放时出现的空白区域。
      }),
      new TileLayer({
        source: new XYZ({
          url:"http://t0.tianditu.com/DataServer?T=cia_w&x={x}&y={y}&l={z}&tk=f0205b3015ed23553ee037f6ecac9b19",
          wrapX: false
        }),
        preload: Infinity,
      }),
      drawVector,
      vectorLayer
    ],
    view: new View({                       // 地图视图
      center: transform([Number(curLoc.value.curLongitude), Number(curLoc.value.curLatitude)],'EPSG:4326', 'EPSG:3857'),
      minZoom:2,// 地图缩放最小级别
      maxZoom:18,//同时设置这两个值（min、maxZoom）之后，就能够限制缩放
      zoom: 16                             // 地图默认缩放级别（打开页面时默认级别）
    }),
    controls: control.defaults().extend([
      scaleLineControl.value, // 比例尺
      new control.MousePosition({
        coordinateFormat: coordinate.createStringXY(4),
        projection: 'EPSG:4326',
        target: mousePositionTxt.value
      })
    ])
  })
  map.value.on('singleclick', e => {
    let elPopup = popupCom.value
    popup.value = new Overlay({
      element: elPopup,
      positioning: 'bottom-center',
      stopEvent: false,
      offset: [0, -10]
    })
    map.value.addOverlay(popup.value)
    let feature = map.value.forEachFeatureAtPixel(e.pixel, feature => feature)

    if (feature) {
      shopPopup.value = true
      let locTime = curLoc.value
      console.log("_______________",locTime)
      elPopup.innerHTML = curLoc.value.LocTime
      let coordinates = feature.getGeometry().getCoordinates()
      setTimeout(() => {
        popup.value.setPosition(coordinates)
      }, 0)
    } else {
      shopPopup.value = false
    }
  })

}

const draw = ref(null)

function drawPoly() {
  if (draw.value != null) {
    map.value.removeInteraction(draw.value)
  }
  if (tool.value != 'None') {
    draw.value = new Draw({
      source: sourceDraw,
      type: tool.value
    })
    map.value.addInteraction(draw.value)
    //当图形框选完之后，就会执行下面，输出点
    draw.value.on('drawend', function (event){
      let geometry = event.feature.getGeometry()
      points.value = geometry.getCoordinates()[0]
      console.log(points.value)
    })

  }
}

function drawExit() {
  if (draw.value) {
    map.value.removeInteraction(draw.value);
  }
  draw.value = null
}

function drawClear() {
  sourceDraw.clear()
  console.log(sourceDraw)

}

onMounted(() => {
  initMap()
})

function mapClick(){
  map.value.on('singleclick', evt => {
    currentCoordinate.value = evt.coordinate // 获取并保存坐标点
  })
}

function showCoordinate(){
  coordinateSign.value = 1
}
</script>

<template>
  <div class="flex w-full gap-1">
    <div id="map1" tabindex="2" class="map1__x grow h-full
    bg-#84b9bf relative" @click="showCoordinate">
      <div class="absolute z-10 w-50 h-9 bg-white rounded-lg px-2  bottom-1 right-1 flex justify-start items-center" ref="mousePositionTxt" v-show="coordinateSign==1">经纬度：</div>

    </div>
    <div ref="popupCom" class="popup" v-show="shopPopup"></div>
    <div class="bg-white w-80 flex flex-col justify-center items-center gap-5">
      <div class="mt-15">用户定位信息展示</div>
      <el-scrollbar height="600px" >
        <div class="bg-white w-80 flex flex-col justify-center items-center gap-2">
          <template v-for="(value,key) in curLoc">
            <!--            <el-card v-if="key!='points'" style="width:280px" shadow="always">-->
            <!--            注意 有些信息 不需要披露（在修改的时候再披露）-->
            <el-card style="width:280px" shadow="always">
              {{key}}:{{value}}
            </el-card>
          </template>
        </div>
      </el-scrollbar>
    </div>
  </div>


</template>

<style scoped>
.popup {
  background: #fff;
  padding: 10px 16px;
  border-radius: 8px;
  box-shadow: 0 0 10px rgba(0, 0, 0, .5);
}
</style>